package models

import (
	"time"
)

// 过期时间（单位：分钟）
var expire = -6 * time.Minute

type User struct {
	ID        uint   `json:"-"`
	User      string `json:"user"`
	Password  string `json:"-"`
	Domain    string `json:"-"`
	UpdatedAt int64  `json:"updated_at"`
	Mac       string `json:"mac"`
}

func (u *User) GetUser(mac string, domain string) bool {
	err := DB.Where("mac = ?", mac).First(u).RecordNotFound()
	if err {
		if DB.Where("updated_at < ?", time.Now().Add(expire).Unix()).Order("mac,id").First(u).RecordNotFound() {
			return false
		}
		u.UpdatedAt = time.Now().Unix()
		u.Mac = mac
		u.Domain = domain
		DB.Save(u)
		return true
	}
	u.UpdatedAt = time.Now().Unix()
	u.Domain = domain
	DB.Save(u)
	return true
}

func (u *User) UpdateUser(mac string) *User {
	err := DB.Where("mac = ?", mac).First(u).RecordNotFound()

	if err {
		return &User{}
	}
	u.UpdatedAt = time.Now().Unix()
	DB.Save(u)

	return u
}

func (u *User) SignOut(mac string) bool {
	err := DB.Where("updated_at > ? AND mac = ?", time.Now().Add(expire).Unix(), mac).First(u).RecordNotFound()
	if err {
		return true
	}

	u.UpdatedAt = 0
	DB.Save(u)
	return true
}
